class Admin::CompaniesController < Admin::ApplicationController
  before_action :set_company, only: [:show, :edit, :update, :destroy, :set_used]

  # GET /admin/companies
  def index
    @companies = Company.where(admin_user_id: current_user.id).order(created_at: :desc).page(params[:page]).per(10)
  end

  # GET /admin/companies/1
  def show
  end

  # GET /admin/companies/new
  def new
    @company = Company.new
  end

  # GET /admin/companies/1/edit
  def edit
  end

  # POST /admin/companies
  def create
    image_file = change_img_params(params[:company][:logo])
    @company = Company.new(company_params.merge({admin_user_id: 1}))

    if @company.save!
      redirect_to admin_companies_url, notice: '保存成功'
    else
      render :new
    end
  end

  # PATCH/PUT /admin/companies/1
  def update
    if @company.update(company_params)
      redirect_to admin_companies_url, notice: '保存成功'
    else
      render :edit
    end
  end

  # DELETE /admin/companies/1
  def destroy
    @company.destroy
    redirect_to admin_companies_url, notice: '删除成功'
  end

  # 设置默认的选择
  def set_used
    @company.update(used: true)
    Company.where(admin_user_id: @company.admin_user_id).where.not(id: @company.id).update_all(used: false)
    redirect_to admin_companies_url, notice: '更改默认公司成功！'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_company
      @company = Company.find_by(id: params[:id], admin_user_id: current_user.id)
    end

    # Only allow a trusted parameter "white list" through.
    def company_params
      params.require(:company).permit(:address, :brief, :content, :logo, :name, :admin_user_id, :phone, :e_mail, :img)
    end
end
